package com.daoshu.mds.system.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
/**
 * @author zhangmingxin
 */
@Slf4j
@Component
public class RequestKit {
    public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
//        if(!StringUtils.isEmpty(ip))
//            return ip;
        log.debug("X-Forwarded-For=============>{}",ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
                log.debug("Proxy-Client-IP=============>{}",ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
                log.debug("WL-Proxy-Client-IP=============>{}",ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
                log.debug("HTTP_CLIENT_IP=============>{}",ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                log.debug("HTTP_X_FORWARDED_FOR=============>{}",ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                log.debug("getRemoteAddr=============>{}",ip);
            }
        }
        log.debug("ip=============>{}",ip);
        if(!StringUtils.isEmpty(ip)){
            String[] ips = ip.split(",");
            if(ips.length>1)
                ip = ips[0];
        }
        return ip;
    }

    private String getIpFromReferer(HttpServletRequest request){
        String url = request.getHeader("Referer");
        log.info("Referer.info====>"+url);
        /**
         * 例：http://localhost:8080/swagger-ui.html
         */
        if(StringUtils.isEmpty(url))
            return "";
        url = url.replace("http://","");
        String[] splitStr = url.split("/");
        String[] splitStrTwo = splitStr[0].split(":");
        return splitStrTwo[0];
    }

}
